package id.co.rho.scoring.cid.client.widgets;

import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.FieldEvent;
import com.extjs.gxt.ui.client.event.Listener;

import com.extjs.gxt.ui.client.util.Util;
import com.google.gwt.user.client.Element;
import gxt.visual.ui.client.implementations.VTextField;

public class DirtyAwareTextField<D> extends VTextField<D> implements DirtyAwareField<D> {
	
	Listener changeListener = new Listener<FieldEvent>() {
	      public void handleEvent(FieldEvent be) {
	        onFieldChange(be);
	      }
	    };
	    
	/**
	 * Dirtyness previous state.
	 */
	boolean dirtyPrevState = false;
	
	public DirtyAwareTextField() {
		super();
		addListener(Events.Change, changeListener);		
	}
	
	@Override
	public void resetDirtyness() {
		dirtyPrevState = false;
		UIHelper.removeDirtyMarker(this);
		onFieldChange(null);
	}

	private void onFieldChange(FieldEvent be) {
		boolean dirty = !Util.equalWithNull(getOriginalValue(),getValue());
		if(dirty != dirtyPrevState) {
			dirtyPrevState = dirty;
			if(dirty) {
				UIHelper.applyDirtyMarker(this);
			}else {
				UIHelper.removeDirtyMarker(this);
			}
		}
	}
	
	 @Override
     public void setMaxLength(int m) {
		 super.setMaxLength(m);
		 if (rendered) {
			 getInputEl().setElementAttribute("maxLength", m);
		 }
     }

     @Override
     protected void onRender(Element parent, int index) {
    	 super.onRender(parent, index);
    	 getInputEl().setElementAttribute("maxLength", getMaxLength());
     }
	
}
